<template>
  <el-dialog
    v-bind="$attrs"
    width="1000px"
    :title="dialogForm.id ? '修改组织' : '新增组织'"
    center
  >
    <el-form
      ref="dialogFormRef"
      :model="dialogForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="组织名称" prop="orgName">
        <el-input v-model="dialogForm.orgName" />
      </el-form-item>
      <el-form-item label="是否为街道" prop="isStreet">
        <el-radio-group v-model="dialogForm.isStreet">
          <el-radio label="1">是</el-radio>
          <el-radio label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="所属监管局"
        prop="jgjName"
        v-if="dialogForm.isStreet === '1'"
      >
        <el-select
          v-model="dialogForm.jgjName"
          placeholder="请选择监管局"
          clearable
          filterable
          @change="changeApplication"
        >
          <el-option
            v-for="item in applicationList"
            :key="item.value"
            :label="item.label"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="所属监管所"
        prop="jgsName"
        v-if="dialogForm.isStreet === '1'"
      >
        <el-select
          v-model="dialogForm.jgsName"
          placeholder="请选择监管所"
          clearable
          filterable
          @change="changeappNameOptions"
        >
          <el-option
            v-for="item in appNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="统一信用代码" prop="uniCode">
        <el-input v-model="dialogForm.uniCode" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onclose()">取消</el-button>
        <el-button type="primary" @click="submit(false)" v-if="isDetail"
          >修改</el-button
        >
        <el-button type="primary" @click="submit(true)" v-if="!isDetail">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent, reactive, ref, toRefs, onMounted } from "vue";
import { apiUrl } from "@/api/api";
import axios from "axios";
import { ElMessage } from "element-plus";

export default defineComponent({
  props: {
    dataForm: Object,
    isDetail: {
      type: Boolean,
      default: false,
    },
    isFabu: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, { emit }) {
    const dialogFormRef = ref();
    const dataMap = reactive({
      dialogForm: {
        isStreet: "0",
      },
      appNameOptions: [],
      applicationList: [],
      applicationObj: {},
      appNameOptionsObj: {},
      rules: {
        orgName: [
          { required: true, message: "请输入组织名称", trigger: "blur" },
        ],
        isStreet: [
          { required: true, message: "请选择是否默认街道", trigger: "change" },
        ],
        uniCode: [
          { required: true, message: "请输入统一信用代码", trigger: "blur" },
        ],
        jgjName: [
          { required: true, message: "请选择监管局", trigger: "change" },
        ],
        jgsName: [
          { required: true, message: "请选择监管所", trigger: "change" },
        ],
      },
    });
    const applicationFun = () => {
      axios({
        method: "get",
        url: apiUrl.baseUrl + "/wl/organ/getOrganList?infoCategory=1",
        data: {},
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
          loginToken: sessionStorage.getItem("loginToken"),
        },
      })
        .then((response) => {
          dataMap.applicationList = response.data.data.map((item) => ({
            value: item.organId,
            label: item.organName,
          }));
        })
        .catch((error) => {
          console.log(error);
        });
    };
    const fetchAppNames = (value) => {
      axios({
        method: "get",
        url:
          apiUrl.baseUrl +
          "/wl/organ/getOrganList?infoCategory=1&parentOrganId=" +
          value,
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
          loginToken: sessionStorage.getItem("loginToken"),
        },
      })
        .then((response) => {
          dataMap.appNameOptions = response.data.data.map((item) => ({
            value: item.organId,
            label: item.organName,
          }));
        })
        .catch((error) => {
          console.log(error);
        });
    };
    const changeApplication = (item) => {
      dataMap.applicationObj = item;
      dataMap.appNameOptionsObj = {};
      dataMap.dialogForm.jgsName = "";
      fetchAppNames(item.value);
    };
    const changeappNameOptions = (item) => {
      dataMap.appNameOptionsObj = item;
    };
    const methodsMap = reactive({
      onclose() {
        emit("close");
      },
      submit(flag) {
        if (flag) {
          dialogFormRef.value.validate((valid) => {
            if (valid) {
              let data = {};
              data.orgName = dataMap.dialogForm.orgName;
              data.uniCode = dataMap.dialogForm.uniCode;
              data.isStreet = dataMap.dialogForm.isStreet;
              if (data.isStreet === "1") {
                data.jgjName = dataMap.applicationObj.label;
                data.jgjCode = dataMap.applicationObj.value;
                data.jgsName = dataMap.appNameOptionsObj.label;
                data.jgsCode = dataMap.appNameOptionsObj.value;
              }
              let params = {};
              params.data = data;
              params.rid = "";
              axios({
                method: "post",
                url: apiUrl.baseUrl + "/wl/auth/org/create",
                data: params,
                headers: {
                  "Content-Type": "application/json;charset=UTF-8",
                  loginToken: sessionStorage.getItem("loginToken"),
                },
              })
                .then((response) => {
                  if (response.data.data.code === "-1") {
                    ElMessage.error(response.data.data.message);
                  } else {
                    setTimeout(() => {
                      emit("getDatas");
                      emit("close");
                    }, 500);
                  }
                })
                .catch((error) => {});
            } else {
              return;
            }
          });
        } else {
          dialogFormRef.value.validate((valid) => {
            if (valid) {
              let data = {};
              data.id = dataMap.dialogForm.id;
              data.orgName = dataMap.dialogForm.orgName;
              data.uniCode = dataMap.dialogForm.uniCode;
              data.isStreet = dataMap.dialogForm.isStreet;
              if (data.isStreet === "1") {
                data.jgjName = dataMap.applicationObj.label;
                data.jgjCode = dataMap.applicationObj.value;
                data.jgsName = dataMap.appNameOptionsObj.label;
                data.jgsCode = dataMap.appNameOptionsObj.value;
              }
              let params = {};
              params.data = data;
              params.rid = "";
              axios({
                method: "post",
                url: apiUrl.baseUrl + "/wl/auth/org/save",
                data: params,
                headers: {
                  "Content-Type": "application/json;charset=UTF-8",
                  loginToken: sessionStorage.getItem("loginToken"),
                },
              })
                .then((response) => {
                  if (response.data.data.code === "-1") {
                    ElMessage.error(response.data.data.message);
                  } else {
                    setTimeout(() => {
                      emit("getDatas");
                      emit("close");
                    }, 500);
                  }
                })
                .catch((error) => {});
            } else {
              return;
            }
          });
        }
      },
    });

    onMounted(() => {
      applicationFun();
      if (props.dataForm) {
        let temp = JSON.parse(JSON.stringify(props.dataForm));
        dataMap.dialogForm = {
          ...temp,
          isStreet: temp.isStreet,
        };
        dataMap.applicationObj.label = temp.jgjName;
        dataMap.applicationObj.value = temp.jgjCode;
        dataMap.appNameOptionsObj.label = temp.jgsName;
        dataMap.appNameOptionsObj.value = temp.jgsCode;
        if (dataMap.dialogForm.jgjCode) {
          fetchAppNames(dataMap.dialogForm.jgjCode);
        }
      }
    });

    return {
      ...toRefs(dataMap),
      ...toRefs(methodsMap),
      changeApplication,
      changeappNameOptions,
      dialogFormRef,
    };
  },
});
</script>
